import {
  addUserChannelApi,
  delUserChannelApi,
  getAllChannelApi,
  getUserChannelApi,
} from '@/api/channel';
import { getLocalChannel, hasToken, setLocalChannels } from '@/utils/storage';
import { AppDispatch } from '..';
import { ChannelActionType, ChannelType } from '../reducers/channel';

export const getAllChannel = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getAllChannelApi();
    dispatch({ type: 'channel/saveChannels', payload: res.data.channels });
    // console.log(res);
  };
};
export const getUserChannel = () => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      const res = await getUserChannelApi();
      dispatch({
        type: 'channel/saveUserChannels',
        payload: res.data.channels,
      });
    } else {
      // 情况1：未登录，去缓存中读取频道列表
      // 缓存中没有数据，重新发送请求
      // console.log(res, 28);
      const localList = getLocalChannel();
      // 从缓存中得到得数据直接渲染
      if (!!localList.length) {
        dispatch({
          type: 'channel/saveUserChannels',
          payload: localList,
        });
      } else {
        // 没有缓存，重新发送请求
        const res = await getAllChannelApi();
        const tenList = res.data.channels.splie(0, 10);
        dispatch({ type: 'channel/saveChannels', payload: tenList });
        // 再保存到缓存中
        setLocalChannels(res.data.channels);
      }
    }
  };
};

// 添加
// export const addUserChannel = (data: ChannelParamsType) => {
export const addUserChannel = (newItem: ChannelType) => {
  return async (dispatch: AppDispatch) => {
    // 新增支持从默认中拿取
    // 如果token存在
    if (hasToken()) {
      await addUserChannelApi({ channels: [newItem] });
      dispatch({
        type: 'channel/updateUserChannels',
        payload: newItem,
      });
      return;
    }
    const localList = getLocalChannel();
    setLocalChannels([...localList, newItem]);
    dispatch({ type: 'channel/updateUserChannels', payload: newItem });
  };
};
// 删除
export const delUserChannelAction = (id: number) => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      await delUserChannelApi(id);
      dispatch({
        type: 'channel/delUserChannels',
        payload: id,
      });
    }
    const localList = getLocalChannel();
    setLocalChannels(localList.filter((v) => v.id !== id));
    dispatch({
      type: 'channel/delUserChannels',
      payload: id,
    });
  };
};

// narbar切换
export const setChannelIdAction = (id: number): ChannelActionType => {
  return {
    type: 'channel/setChannelId',
    payload: id,
  };
};
